import { useEffect, useState } from 'react';
import CommonLoading from '@/components/CommonLoading';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import ProTable from '@/components/ProTable';
import ShopIcons from "@/views/components/ShopIcons";
import { CloudUploadOutlined } from '@ant-design/icons';
import { Button, Space, Tag, message, Result } from 'antd';
import useImportStore from '../../importOrder.js';
import Api from '../../service.js';

const SuccessTag = ({ children }) => {
	return <Tag color="var(--color-success)">{children}</Tag>;
};
const WarningTag = ({ children }) => {
	return <Tag color="var(--color-warning)">{children}</Tag>;
};

//渲染表格
const renderCell = (obj={}, type, row={}) => {
	if(type == 'key2') {
		return (
			<div>
				<div>{obj.value}</div>
				{obj.msg && <SuccessTag>{obj.msg}</SuccessTag>}
			</div>
		)
	} else if(type == 'key4') {
		return (
			<div>
				<ShopIcons type={row?.key13?.value} />
				{obj.value}
			</div>
		)
	} else if(type == 'key8') {
		return (
			<div>
				<div>{obj.value}</div>
				{obj.msg && <WarningTag>{obj.msg}</WarningTag>}
			</div>
		)
	}  else if(type == 'key5') {
		return (
			obj.value ?
			obj.value.split('@').map((v, index) => (
				<div key={index}>{v}</div>
			))
			: null
		)
	} else {
		return obj.value;
	}
}

//预览数据
const TabImportPreview = () => {
	const reviewColumns = [
		{ name: '序号', code: 'key0', width: 80 },
		{ name: '行号', code: 'key1', width: 80 },
		{ name: '店铺订单号', code: 'key2', width: 150, render: (t) => renderCell(t, 'key2') },
		{ name: '平台付款时间', code: 'key3', width: 120, render: (t) => renderCell(t) },
		{ name: '平台/店铺', code: 'key4', width: 120, render: (t, r) => renderCell(t, 'key4', r) },
		{ name: '商品名称', code: 'key5', width: 160, render: (t) => renderCell(t, 'key5') },
		{ name: '发货仓', code: 'key6', width: 80, render: (t) => renderCell(t) },
		{ name: '快递', code: 'key7', width: 80, render: (t) => renderCell(t) },
		{ name: '收货地址', code: 'key8', width: 120, render: (t) => renderCell(t, 'key8') },
		{ name: '买家留言', code: 'key9', width: 120, render: (t) => renderCell(t) },
		{ name: '卖家备注', code: 'key10', width: 120, render: (t) => renderCell(t) },
		{ name: '订单备注', code: 'key11', width: 120, render: (t) => renderCell(t) },
		{ name: '订单状态', code: 'key12', width: 120, render: (t) => renderCell(t) },
	];

	//获取导出id
	const taskId = useImportStore(state => state.taskId);

	const updateTaskId = useImportStore(state => state.updateTaskId);

	//导入进度
	const [exportRate, setRate] = useState(0);

	//正在加载
	const [loading, setLoading] = useState(false);

	//导出状态
	const [exportLoading, setExportLoading] = useState(false);

	//导入结果
	const [exportResult, setExportResult] = useState(false);

	//预览数据
	const [exportData, setExportData] = useState({});

	//异常单数据
	const errorData = exportData.importPreviewErrorResult ? exportData.importPreviewErrorResult.items : [];

	//正常单数据
	const normalData = exportData.importPreviewNormalResult ? exportData.importPreviewNormalResult.items : [];

	useEffect(() => {
		if (taskId) {
			exportResult && setExportResult(false);
			handlePreview();
		}
	}, [taskId])

	//处理预览情况
	const handlePreview = async () => {
		setLoading(true);
		handleExportRate();
	}

	let timer;
	//处理加载进度isResult:true是确定导入进程，false是获取预览进程
	const handleExportRate = async (isResult) => {
		const obj = await getExportRate();
		if (!obj) {
			clearTimeout(timer);
			timer = null;
			setLoading(false);
			setExportResult('接口报错！');
			return;
		}
		//先判断任务是否完成
		if (obj.completed) {
			clearTimeout(timer);
			timer = null;
			setRate(100);
			setLoading(false);
			if(isResult) {
				setExportResult(true);
			} else {
				getPreviewData();
			}
		} else {
			//判断是否中断
			if (obj.interrupted) {
				clearTimeout(timer);
				timer = null;
				setExportResult(obj.message);
				setLoading(false);
			} else {
				const currentRate = ((obj.importedNum / obj.totalNum) * 100).toFixed(2);
				setRate(currentRate);
				clearTimeout(timer);
				timer = setTimeout(() => {
					handleExportRate(isResult)
				}, 1000);
			}
		}
	}

	//获取导出进度
	const getExportRate = async () => {
		const { success, data } = await Api.getImportTaskRate({
			taskId
		})
		if (success) {
			return data;
		}
		return false;
	}

	//获取预览数据
	const getPreviewData = async () => {
		const { success, data } = await Api.getImportPreview({
			taskId
		})
		if (success) {
			setExportData(data);
		}
		setLoading(false);
	}

	//取消导入
	const cancelExport = async (val) => {
		setExportLoading(true);
		const { success } = await Api.executeImportTask({
			taskId,
			type: 2
		});
		setExportLoading(false);
		if (success) {
			message.success('取消导入成功');
			updateTaskId();
		}
	}

	//确定导入
	const exportOrder = async () => {
		if (normalData.length == 0) {
			message.warning('当前文件暂无可用订单,无需导入');
			return;
		}
		setExportLoading(true);
		const { success } = await Api.executeImportTask({
			taskId,
			type: 1
		})
		setExportLoading(false);
		if (success) {
			setLoading(true);
			handleExportRate(true);
		}
	}

	//导出异常订单
	const downloadError = async () => {
		setExportLoading(true);
		const params = {
			id: taskId
		}
		const { success, data } = await Api.downLoadErrorFile(params);
		setExportLoading(false);
		if(success && data) {
			window.open(data);
		}
	}

	//异常订单列
	const errorColumns = [
		{ name: '序号', code: 'key0', width: 80 },
		{ name: '行号', code: 'key1', width: 80 },
		{ name: '店铺订单号', code: 'key2', width: 200 },
		{ name: '异常原因', code: 'key3' },
	]

	const ErrorTableProps = {
		columns: errorColumns,
		data: errorData,
		bordered: true,
		style: {
			maxHeight: 200,
		},
	}

	const ExportTableProps = {
		columns: reviewColumns,
		data: normalData,
		style: {
			maxHeight: 'calc(100vh - 600px)',
		},
	}

	if (!taskId) {
		return (
			<div>请先导入订单数据</div>
		)
	}

	if (loading) {
		return (
			<div>
				订单正在导入中，
				{!isNaN(exportRate) && <span>导入进度<span style={{ margin: '0 4px', fontWeight: 600, color: '#0068FF' }}>{exportRate}</span>%,</span> }
				请稍侯...
			</div>
		)
	}

	//导入结果
	if (exportResult) {
		//代表导入完成
		if (exportRate == 100) {
			return (
				<Result
					status="success"
					title="订单导入成功"
				/>
			)
		}
		return (
			<Result
				status="warning"
				title="订单导入中断"
				subTitle={`中断原因：${exportResult}`}
			/>
		)
	}

	return (
		<>
			<Space direction="vertical" size={16}>
				<SubTitle title={`导入异常结果，共计${errorData.length}行`} suffixStyle={{ marginLeft: '12px' }}  suffix={<Button onClick={downloadError} icon={<CloudUploadOutlined />}>导出异常订单</Button>} as="s2" symbol />
				<ProTable {...ErrorTableProps} />
				<SubTitle title={`订单导入预览，共计${normalData.length}单`} as="s2" symbol suffixStyle={{ marginLeft: '12px' }}  suffix={(
					<>
						<span style={{ marginRight: '12px' }}>部分订单问题预警</span>
						<SuccessTag>系统已存在的订单</SuccessTag>
						<WarningTag>地址不详</WarningTag>
					</>
				)}/>
			<ProTable {...ExportTableProps} />
			</Space>
			<Space style={{ marginTop: '40px'}}>
				<Button type="primary" onClick={exportOrder}>确定导入订单</Button>
				<Button onClick={cancelExport}>取消导入</Button>
			</Space>
			<CommonLoading loading={exportLoading} />
		</>
	);
};
export default TabImportPreview;
